package com.jhd.jiangxi.activity.scan.in.purchase;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.jhd.jiangxi.R;
import com.jhd.jiangxi.UtilHelper;
import com.jhd.jiangxi.activity.main.BaseActivity;
import com.jhd.jiangxi.service.GetVaccineService;
import com.jhd.jiangxi.service.VaccineService;
import com.jhd.jiangxi.vo.ElectCodePackageVoList;
import com.jhd.jiangxi.vo.JsonForResult;
import com.jhd.jiangxi.vo.PiatsInfo;
import com.jhd.jiangxi.vo.PurchaseReceiptDtlVo;
import com.jhd.jiangxi.vo.PurchaseReceiptMstAndDtlVo;
import com.jhd.jiangxi.vo.PurchaseReceiptMstVo;
import com.jhd.jiangxi.vo.StorageInfo;
import com.jhd.jiangxi.vo.VaccineCount;

import net.zigin.commons.util.StringUtil;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import okhttp3.MediaType;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;

import static com.jhd.jiangxi.activity.scan.in.purchase.PurchaseActivity.piatsInfoList;

public class PurchaseStorageActivity extends BaseActivity implements View.OnClickListener {

    private RecyclerView recyclerView;
    private ProgressDialog _progressDialog = null;
    private Button btnCountVaccine, btnSubmitVaccine, btnDelAllVaccine;
    private RecyclerAdapter adapter;
    private AlertDialog _alertDialog = null;
    private List<StorageInfo> storageInfoList;
    List<VaccineCount> vaccineCountList = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_purchase_storage);
        application.setPosition(-1);
        getStorageList();//获取储位列表
        initView();
    }

    private void initView() {
        initHeader("选择入库储位");
        recyclerView = (RecyclerView) findViewById(R.id.rlv_list);
        btnCountVaccine = (Button) findViewById(R.id.btnCountVaccine);
        btnSubmitVaccine = (Button) findViewById(R.id.btnSubmitVaccine);
        btnDelAllVaccine = (Button) findViewById(R.id.btnDelAllVaccine);
        btnCountVaccine.setOnClickListener(this);
        btnSubmitVaccine.setOnClickListener(this);
        btnDelAllVaccine.setOnClickListener(this);
        GridLayoutManager manager = new GridLayoutManager(this, 2);
        recyclerView.setLayoutManager(manager);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
            Intent intent = new Intent("com.jhd.test.broadcast");
            intent.putExtra("type", "0");//0代表返回键
            sendBroadcast(intent);
            onBackPressed();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    protected void initHeader(String title) {
        if ("0".equals(application.getBackSystem())) title = title + "(测试版本)";
        TextView tvTitle = ((TextView) findViewById(R.id.screenTitle));
        if (tvTitle != null) tvTitle.setText(title);
        findViewById(R.id.btnBack).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent("com.jhd.test.broadcast");
                intent.putExtra("type", "0");//0代表返回键
                (v.getContext()).sendBroadcast(intent);
                onBackPressed();
            }
        });
        String userName = application.getRealName() == null ? application.getUserName() : application.getRealName();
        ((TextView) findViewById(R.id.tvHeaderUserName)).setText(userName);
    }

    /*获取储位列表*/
    private void getStorageList() {
        _progressDialog = new ProgressDialog(PurchaseStorageActivity.this);
        _progressDialog.setMessage("正在获取储位信息,请稍等...");
        _progressDialog.show();
        Map<String, Object> params = new LinkedHashMap<String, Object>();
        params.put("deptId", application.getDeptId());
        Retrofit retrofit = UtilHelper.retrofit(application, UtilHelper.baseUrls.EMIAO(application.getBackSystem()));
        VaccineService vs = retrofit.create(VaccineService.class);
        String token = application.getAccessToken();
        Call<JsonForResult> jsonForResultCall = vs.getStorageInfoList(token, params);
        jsonForResultCall.enqueue(new getStorageInfoListCallback());
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btnCountVaccine://跳转到交货单明细页面
                startActivity(new Intent(PurchaseStorageActivity.this, PurchaseDetailActivity.class));
                break;
            case R.id.btnSubmitVaccine://进行提交处理,最好先弹窗提示一下
                if (piatsInfoList.size() > 0) {
                    showDialog(1, v, "确认提交");
                } else {
                    Toast.makeText(PurchaseStorageActivity.this, "你还没有扫描任何疫苗", Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.btnDelAllVaccine://删除本地缓存的扫描数据,最好先弹窗提示操作
                showDialog(2, v, "清空储位");
                break;
        }
    }

    private class getStorageInfoListCallback implements Callback<JsonForResult> {

        @Override
        public void onResponse(Call<JsonForResult> call, Response<JsonForResult> response) {
            if (_progressDialog != null) _progressDialog.cancel();
            try {
                JsonForResult jsonForResult = (JsonForResult) response.body();
                if (jsonForResult != null && jsonForResult.isSuccess() && jsonForResult.getData() != null) {
                    storageInfoList = JSON.parseArray(jsonForResult.getData().toString(), StorageInfo.class);
                    adapter = new RecyclerAdapter(storageInfoList);
                    recyclerView.setAdapter(adapter);
                } else {
                    if (jsonForResult != null && jsonForResult.getMessage() != null && "".equals(jsonForResult.getMessage()) == false) {
                        UtilHelper.alertMsg(PurchaseStorageActivity.this, "错误", jsonForResult.getMessage());
                    }
                }
            } catch (Exception e) {
                Toast.makeText(getApplicationContext(), e.getLocalizedMessage(), Toast.LENGTH_SHORT).show();
            }
        }

        @Override
        public void onFailure(Call<JsonForResult> call, Throwable t) {
            if (_progressDialog != null) _progressDialog.cancel();
            String msg = "网络异常!";
            if (StringUtil.isNullOrEmpty(t.getMessage()) == false) msg = msg + t.getMessage();
            UtilHelper.alertMsg(PurchaseStorageActivity.this, "错误", msg);
        }
    }

    private void savePurchaseReceiptMstAndDtlFromSale() {
        Map<String, Object> params = new LinkedHashMap<String, Object>();
        PurchaseReceiptMstAndDtlVo purchaseReceiptMstAndDtlVo = new PurchaseReceiptMstAndDtlVo();
        PurchaseReceiptMstVo purchaseReceiptMstVo = new PurchaseReceiptMstVo();
        purchaseReceiptMstVo.setApprovalId(application.getApprovalId());
        if(application.getArrivalTime()!=null)purchaseReceiptMstVo.setArrivalTime(getDate(application.getArrivalTime()));
        if(application.getRunTime()!=null)purchaseReceiptMstVo.setRunTime(getDate(application.getRunTime()));
        purchaseReceiptMstVo.setCategory(piatsInfoList.get(0).getCategory());
        if(application.getColdChainType()!=null){
            int coldChainType = Integer.valueOf(application.getColdChainType());
            if (coldChainType > 10) {//小于10的时候,在前面补0
                purchaseReceiptMstVo.setColdChainType(application.getColdChainType());
            } else {
                purchaseReceiptMstVo.setColdChainType("0" + application.getColdChainType());
            }
        }
        purchaseReceiptMstVo.setHandleDate(getTime(new Date()));
        purchaseReceiptMstVo.setHandlerName(application.getUserName());
        purchaseReceiptMstVo.setDeptId(application.getDeptId());
        purchaseReceiptMstVo.setPriceBookNo(application.getPriceNoIn());
        purchaseReceiptMstVo.setPriceBookMstId(application.getPriceBookMstId());
        purchaseReceiptMstVo.setPurchaseType("1");//采购入库写1
        if (application.getRemark() == null) {
            purchaseReceiptMstVo.setRemark("");//备注
        } else {
            purchaseReceiptMstVo.setRemark(application.getRemark());//备注
        }
        purchaseReceiptMstVo.setSourceId("");//
        purchaseReceiptMstVo.setSupplyDeptName(application.getSupplyDeptName());
        purchaseReceiptMstVo.setSupplyDeptId(application.getSupplyDeptId());
        purchaseReceiptMstVo.setTransformUnit(application.getTransformId());
        purchaseReceiptMstVo.setTransformUnitName(application.getTransformName());
        purchaseReceiptMstVo.setUserId(application.getUserId());
        purchaseReceiptMstVo.setUserName(application.getUserName());
        purchaseReceiptMstVo.setSourceType("0");//sourceType为0代表来源类型是自制单据,不用传
        purchaseReceiptMstAndDtlVo.setPurchaseReceiptMstVo(purchaseReceiptMstVo);
        List<PurchaseReceiptDtlVo> purchaseReceiptDtlVoList = new ArrayList<PurchaseReceiptDtlVo>();

        System.out.println("dddd:"+JSON.toJSONString(piatsInfos));
        for (int i = 0; i < piatsInfoList.size(); i++) {
            PurchaseReceiptDtlVo purchaseReceiptDtlVo = new PurchaseReceiptDtlVo();
            purchaseReceiptDtlVo.setCategory(piatsInfoList.get(i).getCategory());
            purchaseReceiptDtlVo.setExpiryDate(piatsInfoList.get(i).getExpireDate());
            purchaseReceiptDtlVo.setIsThirdParty("1");//先默认没有第三方
            purchaseReceiptDtlVo.setLotNumber(piatsInfoList.get(i).getBatchNo());
            purchaseReceiptDtlVo.setManufacturerId(piatsInfoList.get(i).getProduceMappingId());
            purchaseReceiptDtlVo.setManufacturerName(piatsInfoList.get(i).getProduceName());
            purchaseReceiptDtlVo.setPropertyId(piatsInfoList.get(i).getPropertyId());
            purchaseReceiptDtlVo.setQuantity(piatsInfoList.get(i).getPkgAmount());
            purchaseReceiptDtlVo.setServicePrice(piatsInfoList.get(i).getServicePrice());
            purchaseReceiptDtlVo.setStorage(piatsInfoList.get(i).getStorageName());
            purchaseReceiptDtlVo.setStorageId(piatsInfoList.get(i).getStorageId());
            purchaseReceiptDtlVo.setUnitPrice(piatsInfoList.get(i).getUnitPrice());
            purchaseReceiptDtlVo.setVaccineId(piatsInfoList.get(i).getMappingId());
            purchaseReceiptDtlVo.setVaccineName(piatsInfoList.get(i).getPhysicName());
            purchaseReceiptDtlVo.setVaccineLotsId(piatsInfoList.get(i).getBatchId());
            purchaseReceiptDtlVo.setVaccineSpec(piatsInfoList.get(i).getPkgSpec());
            purchaseReceiptDtlVo.setVaccineDose(piatsInfoList.get(i).getPrepnSpec());
//            purchaseReceiptDtlVo.setContractNo(piatsInfoList.get(i).getContractNoList()==null?null:piatsInfoList.get(i).getContractNoList().get(0));
            ElectCodePackageVoList electCodePackageVoList = new ElectCodePackageVoList();
            electCodePackageVoList.setCodeLevel(piatsInfoList.get(i).getCodeLevel());
            electCodePackageVoList.setElectCode(piatsInfoList.get(i).getCode());
            electCodePackageVoList.setQuantity(piatsInfoList.get(i).getPkgAmount());
            purchaseReceiptDtlVo.setElectCodePackageVoList(electCodePackageVoList);
            purchaseReceiptDtlVoList.add(purchaseReceiptDtlVo);
        }
        purchaseReceiptMstAndDtlVo.setPurchaseReceiptDtlVoList(purchaseReceiptDtlVoList);
//        params.put("purchaseReceiptMstAndDtl", purchaseReceiptMstAndDtlVo);
        params.put("deptId", application.getDeptId());
        params.put("userId", application.getUserId());
        params.put("type","01");//不用传了
        params.put("purchaseReceiptDtlVoList", purchaseReceiptDtlVoList);
        params.put("purchaseReceiptMstVo", purchaseReceiptMstVo);
        Retrofit retrofit = UtilHelper.retrofit(application, UtilHelper.baseUrls.EMIAO(application.getBackSystem()));
        GetVaccineService vs = retrofit.create(GetVaccineService.class);
        String token = application.getAccessToken();
        String ss=JSON.toJSONString(params);
        System.out.println("dddd:"+ss);
        System.out.println("dddd:"+token);
        RequestBody requestBody = RequestBody.create(MediaType.parse("Content-Type, application/json"),
                JSON.toJSONString(params));
        Call<JsonForResult> jsonForResultCall = vs.savePurchaseReceiptMstAndDtl(token, requestBody);
        jsonForResultCall.enqueue(new getSavePurchaseReceiptMstAndDtlFromSale());
    }

    private class getSavePurchaseReceiptMstAndDtlFromSale implements Callback<JsonForResult> {

        @Override
        public void onResponse(Call<JsonForResult> call, Response<JsonForResult> response) {
            if (_progressDialog != null) _progressDialog.cancel();
            try {
                JsonForResult jsonForResult = (JsonForResult) response.body();
                if (jsonForResult != null && jsonForResult.isSuccess()) {
                    Toast.makeText(PurchaseStorageActivity.this, "入库成功", Toast.LENGTH_SHORT).show();
                    Intent intent = new Intent("com.jhd.test.broadcast");
                    intent.putExtra("type", "1");//1代表入库成功
                    sendBroadcast(intent);
                    onBackPressed();
                } else {
                    if (jsonForResult != null && jsonForResult.getMessage() != null && "".equals(jsonForResult.getMessage()) == false) {
                        UtilHelper.alertMsg(PurchaseStorageActivity.this, "错误", jsonForResult.getMessage());
                    }
                }
            } catch (Exception e) {
                Toast.makeText(getApplicationContext(), e.getLocalizedMessage(), Toast.LENGTH_SHORT).show();
            }
        }

        @Override
        public void onFailure(Call<JsonForResult> call, Throwable t) {
            String msg = "网络异常!";
            if (StringUtil.isNullOrEmpty(t.getMessage()) == false) msg = msg + t.getMessage();
            UtilHelper.alertMsg(PurchaseStorageActivity.this, "错误", msg);
        }
    }


    public void showDialog(int dex, View v, String title) {
        AlertDialog.Builder alertBuilder = new AlertDialog.Builder(v.getContext());
        alertBuilder.setTitle(title);
        if (title.equals("确认提交")) {
            String msg = "";
            vaccineCountList.clear();
            for (PiatsInfo piatsInfo : piatsInfoList) {
                VaccineCount vaccineCount = new VaccineCount();
                vaccineCount.setName(piatsInfo.getPhysicName());
                if (!vaccineCountList.contains(vaccineCount)) {
                    vaccineCountList.add(vaccineCount);
                }
            }
            for (VaccineCount vaccineCount : vaccineCountList) {
                int num = 0;
                for (PiatsInfo piatsInfo : piatsInfoList) {
                    if (piatsInfo.getPhysicName().equals(vaccineCount.getName())) {
                        num = num + Integer.valueOf(piatsInfo.getPkgAmount());
                    }
                }
                vaccineCount.setNum(num);
            }
            for (int i = 0; i < vaccineCountList.size(); i++) {
                msg = msg + "疫苗名称:" + vaccineCountList.get(i).getName() + " 扫码数:" + vaccineCountList.get(i).getNum() + "\n";
            }
            alertBuilder.setMessage("已扫疫苗 " + msg + "你确定保存吗?");
        } else if (title.equals("清空储位")) {
            alertBuilder.setIcon(R.mipmap.dialog_alert);
            alertBuilder.setMessage("你确定清空所有储位吗");
        } else if (title.equals("选择储位")) {
            alertBuilder.setMessage("你确定选择该储位:" + application.getStorageName() + " 进行入库吗?");
        }
        alertBuilder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                if (dex == 1) {//保存所有数据
                    savePurchaseReceiptMstAndDtlFromSale();
                } else if (dex == 2) {//清空储位数据
                    piatsInfoList.clear();
                    adapter = new RecyclerAdapter(storageInfoList);
                    recyclerView.setAdapter(adapter);
                    Intent intent = new Intent("com.jhd.test.broadcast");
                    intent.putExtra("type", "2");//2代表清空扫描
                    sendBroadcast(intent);
                } else if (dex == 3) {
                    PurchaseStorageActivity.this.finish();
                }
                _alertDialog.dismiss();
            }
        });

        alertBuilder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                _alertDialog.dismiss();
            }
        });

        _alertDialog = alertBuilder.create();
        _alertDialog.show();
    }

    public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.ViewHolder> {
        private List<StorageInfo> storageList;

        public RecyclerAdapter(List<StorageInfo> storageList) {
            this.storageList = storageList;
        }

        @NonNull
        @Override
        public RecyclerAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_storage2, parent, false);
            RecyclerAdapter.ViewHolder viewHolder = new RecyclerAdapter.ViewHolder(itemView);
            return viewHolder;
        }

        @Override
        public void onBindViewHolder(@NonNull RecyclerAdapter.ViewHolder holder, int position) {
            holder.storageName.setText(storageList.get(position).getName());
            holder.brand.setText(storageList.get(position).getBrand());
            int num = 0;
            if (piatsInfoList.size() > 0) {
                for (int i = 0; i < piatsInfoList.size(); i++) {
                    if (piatsInfoList.get(i).getPosition() == position) {
                        num = num + Integer.valueOf(piatsInfoList.get(i).getPkgAmount());
                    }
                    holder.num.setText(String.valueOf(num));
                }
            } else {
                holder.num.setText("0");
            }

            if (application.getPosition() == position) {
                holder.storageName.setTextColor(getResources().getColor(R.color.colorBlue));
                holder.brand.setTextColor(getResources().getColor(R.color.colorBlue));
                holder.brand2.setTextColor(getResources().getColor(R.color.colorBlue));
                holder.num2.setTextColor(getResources().getColor(R.color.colorBlue));
                holder.rlStorage.setBackgroundResource(R.drawable.storage_background_2);
            } else {
                if (num != 0) {
                    holder.rlStorage.setBackgroundResource(R.drawable.storage_background_1);
                } else {
                    holder.rlStorage.setBackgroundResource(R.drawable.storage_background_3);
                }
                holder.storageName.setTextColor(getResources().getColor(R.color.colorBlack));
                holder.brand.setTextColor(getResources().getColor(R.color.colorText));
                holder.brand2.setTextColor(getResources().getColor(R.color.colorText));
                holder.num2.setTextColor(getResources().getColor(R.color.colorText));
            }
            holder.rlStorage.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    application.setStorageName(storageList.get(position).getName());
                    application.setStorageId(storageList.get(position).getId());
                    application.setPosition(position);
                    notifyDataSetChanged();
                    showDialog(3, v, "选择储位");
                }
            });
//
        }

        @Override
        public int getItemCount() {
            return storageList.size();
        }


        class ViewHolder extends RecyclerView.ViewHolder {
            TextView storageName, brand, num, brand2, num2; //储位名称，温度，品牌，入库数
            RelativeLayout rlStorage;

            public ViewHolder(View itemView) {
                super(itemView);
                this.storageName = itemView.findViewById(R.id.tvStorage);
                this.brand = itemView.findViewById(R.id.tv_Device);
                this.brand2 = itemView.findViewById(R.id.tv_Device2);
                this.num = itemView.findViewById(R.id.tv_InNo);
                this.num2 = itemView.findViewById(R.id.tv_InNo2);
                this.rlStorage = itemView.findViewById(R.id.rlStorage);
            }

        }
    }

}